<?php

namespace app\admin\controller;

use app\common\DictConstant;

use app\admin\model\Menu;

use think\Request;

/**
 * 设置管理员
 * Class Setadmin
 * @package app\admin\controller
 */
class Setadmin extends Base
{

    public function _initialize(){
        parent::_initialize();

        $this->model = 'user';
        $defaultWhere['status'] = 1;
        $defaultWhere['is_admin'] = 1;
        $defaultWhere['type'] = 1;
        $this->defaultWhere = $defaultWhere;
        $this->searchFields = [
            'p_name' => [
                'label'     => '姓名',
                'field'     => 'p_name',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
            'p_phone' => [
                'label'     => '手机',
                'field'     => 'p_phone',
                'type'      => 'text',
                'disabled'  => false,
                'condition' => 'like'
            ],
        ];
        $this->redirect = 'admin/setadmin/index';

        if($this->request->action() == 'add' || $this->request->action() == 'edit') {
            $menus = [];
            $recursive = function ($parentId) use (&$recursive, &$childs) {
                $results = Menu::where(['status' => 1, 'isRole' => 1, 'parentId' => $parentId])->field('id, menu_name, parentId')->order('sorting')->select();
                foreach($results as $key => $value){
                    $childs[$value['id']] = $value->toArray();

                    $recursive($value['id']);
                }

                return $childs;
            };

            $data = Menu::where(['parentId' => 0])->field('id, menu_name, parentId')->order('sorting')->select();
            foreach ($data as $key => $menu) {
                $childs = $recursive($menu['id']);
                if($childs){
                    $menus[$menu['id']] = $childs;
                }

                $childs = [];
            }
            /*
            $menus = Menu::where(['status' => 1, 'isRole' => 1])->field('id, name, parentId')->select();
            $menuMap = [];
            foreach ($menus as $key => $menu) {
                $menuMap[$menu['parentId']][] = $menu->toArray();
            }
            */
            $this->assign('menu', $menus);
        }
    }

    public function index(){
        $request = $this->request;
        if($request->isAjax()){
            $param = $request->param();
            $model = model($this->model);
            // 每页起始条数
            $start = $param['start'];
            // 每页显示条数
            $length = $param['length'];
            // 排序条件
            $columns = $param['order'][0]['column'];
            $order = $param['columns'][$columns]['data'].' '.$param['order'][0]['dir'];

            $where = $this->getFilterWhere($request);
            if($this->defaultWhere){
                //$model = $model->where($this->defaultWhere);
                $where = array_merge($where, $this->defaultWhere);
            }
            /*if($this->defaultOrder){
                $model = $model->order($this->defaultOrder);
            }*/

            $list = $model->where($where)->limit($start, $length)->order($order)->select();
            foreach ($list as &$item) {

                $department = \app\admin\model\Department::where(['id' => $item->departmentId])->value('name');

                $item->department = $department;
            }
            $count = $model->where($where)->count();

            $result = [
                'status' => '1',
                'draw' => $param['draw'],
                'data' => $list,
                'recordsFiltered' => $count,
                'recordsTotal' => $count,
            ];

            return json($result);
        }
        return parent::index();
    }

    public function add(){
        $Department = \app\admin\model\Department::where('status',1)->select();

        return $this->fetch('',[
            'department' => $Department,
        ]);
    }

    public function addPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['personId']) || empty($param['departmentId'])){
                return $this->error('缺少参数');
            }
            $User = \app\admin\model\User::get($param['personId']);
            if($User && $User->status == 1 && $User->type == 1 && $User->is_admin == 0){
                $User->is_admin = 1;
                if(isset($param['menuId']) && !empty($param['menuId'])){
                    $menuIds = (array)$param['menuId'];
                    foreach ($menuIds as $v){
                        $Menu = \app\admin\model\Menu::get($v);
                        if($Menu['parentId'] != 0){
                            $menuIds[] = (string)$Menu['parentId'];
                        }
                    }
                }
                $menuIds[] = DictConstant::HOMEACCESS;
                $access = implode(',',array_unique($menuIds));
                $User->menuId = $access;
                if($User->save()){
                    return $this->success('添加成功',$this->redirect);
                }else{
                    return $this->error('添加失败');
                }
            }else{
                return $this->error('该用户不可以分配管理员');
            }
        }else{
            return $this->error('非法请求');
        }
    }

    public function edit(Request $request){
       $param = $request->param();
       if(empty($param['id'])){
           return $this->error('缺少参数');
       }
       $User = \app\admin\model\User::get($param['id']);
        if($User && $User->type == 1 && $User->is_admin == 1){
           $Departmentname =  \app\admin\model\Department::where('id',$User->departmentId)->value('name');
           $User['Departmentname'] = $Departmentname;

        }else{
            return $this->error('编辑的用户异常');
        }

        return $this->fetch('',[
            'info' => $User,
        ]);
    }

    public function editPost(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return $this->error('缺少参数');
            }
            $User = \app\admin\model\User::get($param['id']);
            if($User && $User->status == 1 && $User->type == 1 && $User->is_admin == 1){
                if(isset($param['menuId']) && !empty($param['menuId'])){
                    $menuIds = (array)$param['menuId'];
                    foreach ($menuIds as $v){
                        $Menu = \app\admin\model\Menu::get($v);
                        if($Menu['parentId'] != 0){
                            $menuIds[] = (string)$Menu['parentId'];
                        }
                    }
                }
                $menuIds[] = DictConstant::HOMEACCESS;
                $access = implode(',',array_unique($menuIds));
                $User->menuId = $access;
                if($User->save() !== false){
                    return $this->success('修改成功',$this->redirect);
                }else{
                    return $this->error('修改失败');
                }
            }else{
                return $this->error('该用户身份异常');
            }

        }else{
            return $this->error('非法请求');
        }
    }

    /**
     * 筛选条件
     */
    public function getFilterWhere($request){
        $param = $request->param();
        $where = [];
        if($param['search']['value']) {
            $filter = json_decode($param['search']['value'],true);
            if(isset($filter['p_name']) && $filter['p_name']){
                $where['p_name'] = ['like', '%'.$filter['p_name'].'%'];
            }
            if(isset($filter['p_phone']) && $filter['p_phone']){
                $where['p_phone'] = $filter['p_phone'];
            }
        }

        return $where;
    }
}